<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
  const departments = [
    {name : '冯',id : 1 , pid: 0},
    {name : '马',id :2 , pid: 0},
    {name : '王',id : 3 , pid: 0},
    {name : '东',id : 4 , pid: 1},
    {name : '南',id : 5 , pid: 2},
    {name : '西',id : 6 , pid: 3},
  ]

  function listData(list,pid) {
    const arr = []
list.forEach(item => {
if(item.pid ===pid) {
  const children = listData(list,item.id)
  if(children.length) {
    item.children = children
  }
  arr.push(item)
}
});
return arr
  }
  console.log(listData(departments,0));
  </script>
</body>

</html>
